package com.basiclib.view

import android.content.Context
import android.graphics.Color
import com.google.android.material.appbar.AppBarLayout
import androidx.appcompat.widget.Toolbar
import android.util.AttributeSet
import android.view.LayoutInflater
import android.widget.TextView
import com.base.lib.R

/**
 * @author harisucici
 * @version 2019/4/9 15:52
 * name
 * todo
 * @email harisucici@gmail.com
 */
class MyToolbar(context: Context, attrs: AttributeSet) : AppBarLayout(context, attrs) {

    val toolbar: Toolbar
    private val toolbarTitle: TextView
    private var title: String? = null
    private var colorString: String? = null

    init {
        handleAttrs(context, attrs)
        LayoutInflater.from(context).inflate(R.layout.include_toolbar, this)
        toolbar = findViewById(R.id.toolbar)
        toolbar.title = ""
        toolbar.setBackgroundColor(Color.parseColor(colorString))


        //给顶部的view添加paddingTop
        val height = getStatusBarHeight(context)
        toolbar.setPadding(
            paddingRight, height + paddingTop,
            paddingLeft, paddingBottom
        )

        toolbarTitle = findViewById(R.id.toolbar_title)
        toolbarTitle.text = title




    }

    private fun handleAttrs(context: Context, attrs: AttributeSet) {
        val ta = context.obtainStyledAttributes(attrs, R.styleable.MyToolbar)
        title = ta.getString(R.styleable.MyToolbar_tb_title)
        colorString = ta.getString(R.styleable.MyToolbar_tb_color)
        if (colorString == null) {
            colorString = "#23AFDC"
        }
        ta.recycle()
    }

    companion object {

        //动态获取statusBar的高度
        private var sHeight = -1

        fun getStatusBarHeight(context: Context): Int {
            if (sHeight == -1) {
                //获取status_bar_height资源的ID
                val resourceId = context.resources.getIdentifier("status_bar_height", "dimen", "android")
                if (resourceId > 0) {
                    //根据资源ID获取响应的尺寸值
                    sHeight = context.resources.getDimensionPixelSize(resourceId)
                }
            }
            return sHeight
        }
    }

}